import json
from django.http import StreamingHttpResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from aiohttp import ClientSession
import requests
import asyncio
from openai import OpenAI
from http import HTTPStatus
from dashscope import Generation




@csrf_exempt
def chat(request):
    if request.method == 'POST':
        # 获取客户端的请求数据
        data = json.loads(request.body) 
        temperature = data.get("temperature") if data.get("temperature") else 0.9
        top_p = data.get("top_p") if data.get("top_p") else 0.9
        
        header = request.headers
        print(header)
        if header.get("Authorization") == "Bearer 123":
        # if data["api-key"] == "123":            
            # 使用http接口
            # headers = {
            #     "Content-Type": "application/json"
            # } 
            # url = "http://localhost:1234/v1/chat/completions"
            # if data["model"] == "qwen-plus":
            #     url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
            #     headers = {
            #         "Authorization": "Bearer sk-a8e58eceb67c476183487883884d1713",
            #         "Content-Type": "application/json"
            #     }              
            
            # return JsonResponse( requests.post(url,headers=headers, json=data).json(),  status=200)
            
            print("success")

            # 基于openai的sdk
            client = OpenAI(base_url="http://localhost:1234/v1", api_key="none")

            completion = client.chat.completions.create(
                model=data.get("model"),
                messages=data.get("messages"),
                temperature=temperature,
                top_p=top_p,
            )
            return JsonResponse({"result": completion.choices[0].message.content}, status=200)
        
        else:
            return JsonResponse({"error": "Invalid API key"}, status=401)
        
    return JsonResponse({"error": "Only POST method is allowed"}, status=405)


    
    
   
@csrf_exempt
def ssechat1(request):
    if request.method == 'POST':
        # 从请求中获取数据
        data = json.loads(request.body)
        
        
        
        if data["api-key"] == "123": 
            
            # client = OpenAI(base_url="http://localhost:1234/v1", api_key="none")

            # responses = client.chat.completions.create(
            #     model=data.get("model"),
            #     messages=data.get("messages"),
            #     stream=data.get("stream")
            # )
            
            responses = Generation.call(model=data.get("model"),  
                messages=data.get("messages"),  
                result_format='message',
                stream=True,  # 设置输出方式为流式输出
                incremental_output=True  # 增量式流式输出
            ) 
            response = StreamingHttpResponse(daul_responses(responses),content_type='text/event-stream')
            
            response["Cache-Control"] = "no-cache"
            
            return response
        
        
        return StreamingHttpResponse("Invalid API key", status=405, content_type='text/event-stream')
    
    return StreamingHttpResponse("Only POST method is allowed", status=405, content_type='text/event-stream')
            
def daul_responses(responses):
    for response in responses:
        if response.status_code == HTTPStatus.OK:
            data1 = response.output.choices[0]['message']['content']
            data = f"data: {data1}\n\n"
            if data1:
                yield data.encode('utf-8')  # 必须编码为字节串
            else:
                return "no message"          
            

def stream_response(responses):
    for chunk in responses.iter_content(chunk_size=None):
        if chunk:            
            yield chunk
    

@csrf_exempt
def ssechat(request):
    if request.method == 'POST':
        # 从请求中获取数据
        data = json.loads(request.body)
        
        if data["api-key"] == "123":            
            # 使用http接口
            headers = {
                "Content-Type": "application/json"
            } 
            url = "http://localhost:1234/v1/chat/completions"
            if data["model"] == "qwen-plus":
                headers = {
                    "Authorization": "Bearer sk-a8e58eceb67c476183487883884d1713",
                    "Content-Type": "application/json"
                }   
                url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"           
            response = requests.post( url, json=data,headers=headers, stream=True )
        # 检查响应状态码
        if response.status_code != 200:
            return StreamingHttpResponse(response.text, status=response.status_code, content_type='text/event-stream')

        # 流式返回响应
        return StreamingHttpResponse(stream_response(response), status=200,content_type='text/event-stream')
    else:
        return StreamingHttpResponse("Method not allowed", status=405, content_type='text/event-stream')
                    
        

       

        